package com.dq.config;

import com.dq.component.CustomSavedRequestAwareAuthenticationSuccessHandler;
import com.dq.component.MySessionExpiredStrategy;
import com.dq.mapper.GoodsMapper;
import com.dq.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
import org.thymeleaf.extras.springsecurity5.util.SpringSecurityContextUtils;

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    UserServiceImpl userService;

    @Autowired
    MySessionExpiredStrategy mySessionExpiredStrategy;

    @Autowired
    CustomSavedRequestAwareAuthenticationSuccessHandler customSavedRequestAwareAuthenticationSuccessHandler;

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    /**
     * 使用自定义用户服务校验登录信息
     *
     * @param
     * @throws Exception **/


    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //没有权限跳转页面
        http.exceptionHandling().accessDeniedPage("/views/reaction/403.html");

        http.authorizeRequests().antMatchers("/","/assets/**","/picture/**","/a1",
                "/register","/a2","/goods/showAll",
                "/vendor/**","/js/**","/pagination/**","/css/**","/images/**","/keySearch","/toForgotPassword","/findAccount").permitAll();



        //开启自动配置的登录功能：如果没有权限，就会跳转到登录页面！
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败


        http.formLogin()
                .usernameParameter("id")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login222").failureUrl("/").successHandler(customSavedRequestAwareAuthenticationSuccessHandler); // 登陆表单提交请求

//successForwardUrl("/").
        //开启自动配置的注销的功能
        // /logout 注销请求
        // .logoutSuccessUrl("/"); 注销成功来到首页

        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
        http.logout().logoutSuccessUrl("/");

        http.authorizeRequests() // 授权配置
                .antMatchers("/","/index-5","/toLogin","/login","/session/invalid",
                        "/index","/assets/**","/login.html","/a1","/toRegister","/register").permitAll() // 无需认证的请求路径
                .anyRequest()  // 所有请求
                .authenticated();// 都需要认证


        http .sessionManagement() // 添加 Session管理器
                .invalidSessionUrl("/") // Session失效后跳转到这个链接
                .maximumSessions(1)
                .expiredSessionStrategy(mySessionExpiredStrategy);


        //记住我
        http.rememberMe().rememberMeParameter("remember");
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {




        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");

        // 用户登录信息校验使用自定义 userService
        // 还需要注意密码加密与验证需要使用同一种方式
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());


    }
}